package com.tutu.elementui.controller;

import com.tutu.elementui.common.R;
import com.tutu.elementui.entity.Blog;
import com.tutu.elementui.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Program: SpringBoot
 * @Description:
 * @Author: JK.TuTu
 * @Create: 2022-11-02 10:21
 **/
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("blog")
public class BlogController {

    @Autowired
    private BlogService blogService;

    /**
     * 查询所有blog
     *
     * @return
     */
    @GetMapping("findAll")
    public R findAll() {
        List<Blog> blogs = blogService.findAll();
        return R.success(blogs);
    }


    /**
     * 提交或修改博客
     *
     * @param blog
     * @return
     */
    @PostMapping("saveOrUpdateBlog")
    public R saveBlog(@RequestBody Blog blog) {
        log.info("提交的blog:{}", blog);
        try {
            if (blog.getId() != null) {
                blogService.updateBlog(blog);
            } else {
                blogService.saveBlog(blog);
            }
        } catch (Exception e) {
            return R.error("提交博客失败!");
        }
        return R.success("提交博客成功!");
    }

    /**
     * 删除博客
     *
     * @param id
     * @return
     */
    @DeleteMapping("deleteBlog/{id}")
    public R deleteBlog(@PathVariable("id") Integer id) {
        log.info("删除的博客id:{}", id);
        try {
            blogService.deleteBlog(id);
            return R.success("删除博客成功!");
        } catch (Exception e) {
            return R.error("删除博客失败!");
        }
    }

    /**
     * 根据id查询博客
     *
     * @param id
     * @return
     */
    @GetMapping("findBlogById/{id}")
    public R findBlogById(@PathVariable("id") Integer id) {
        Blog blog = blogService.findBlogById(id);
        if (ObjectUtils.isEmpty(blog)) {
            return R.error("查询博客失败!");
        }
        return R.success(blog);
    }

    /**
     * 分页查询
     *
     * @param page     当前页数
     * @param pageSize 每页显示数
     * @return
     */
    @GetMapping("searchForPage/{page}/{pageSize}")
    public R searchForPage(@PathVariable("page") Integer page,
                           @PathVariable("pageSize") Integer pageSize) {
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 3 : pageSize;
        int pageNum = (page - 1) * pageSize;
        List<Blog> blogs = blogService.searchForPage(pageNum, pageSize);
        return R.success(blogs);
    }

    /**
     * 查询总条数
     *
     * @return
     */
    @GetMapping("findTotal")
    public R findTotal() {
        int total = blogService.findTotal();
        return R.success(total);
    }

}
